package org.oos.services;

import java.util.Random;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.oos.services.log.Logger;
import static org.oos.services.Constants.*;

public class APPDataSource
{
	private Logger log;
	
	//private final String API_BASE_URL = "http://11870.com/api/v1";
	private final String CHARSET = "UTF-8";
	private final String CONTENT_TYPE = "application/atom+xml";
	
	private String email;
	private String authToken;
	
	public APPDataSource(String email, String authToken, Logger log) {
		super();
		this.email = email;
		this.authToken = authToken;
		this.log = log;
	}

	public void post(String url, String content) throws OOSException
	{
		try
		{
			PostMethod post = new PostMethod(url);
	        RequestEntity entity = new StringRequestEntity(content, CONTENT_TYPE, CHARSET);
	        post.setRequestEntity(entity);
	        post = (PostMethod) injectWSSEHeaders(post, email, authToken);

	        HttpClient httpclient = new HttpClient();
	        try
	        {
	            int result = httpclient.executeMethod(post);
	            log.d(LOG_TAG, "Response status code: " + result);
	            log.d(LOG_TAG, "Response body: "+post.getResponseBodyAsString());
	        }
	        finally
	        {
	            // Release current connection to the connection pool
	            post.releaseConnection();
	        }
		}
		catch (Exception e)
		{
			throw new OOSException("could not send post method, perhaps application is not authenticated", e); 
		}
	}

	public static HttpMethod injectWSSEHeaders(HttpMethod method, String email, String authToken) throws OOSException
	{
		if (email==null || authToken==null) throw new OOSException("missing user authorization");
		
		Base64 b64 = new Base64();
		String created = new Long(System.currentTimeMillis()).toString();
		String nonce = (new Long((new Random()).nextLong())).toString();

		String digest = new String(b64.encode(DigestUtils.sha(nonce + created + authToken)));

		method.addRequestHeader("Authorization", "WSSE realm=\"11870.com\", profile=\"UsernameToken\"");
		method.addRequestHeader("X-WSSE", "UsernameToken Username=\"" + email + "\", PasswordDigest=\"" + digest + "\", Nonce=\"" + nonce + "\", Created=\"" + created + "\"");
		return method;
	}
}
